package com.wl.dzt.sys.controller.action;

import com.wl.dzt.sys.controller.fileupload.FileUploadTemplate;
import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.controller.result.ActionResult;
import com.wl.dzt.sys.controller.result.FormResult;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.core.dao.curd.validate.Validate;
import com.wl.dzt.sys.util.StringUtil;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 删除动作
 * 用于处理删除请求
 * 根据参数执行删除动作
 * 支持删除验证和自定义验证
 */
@Component
public class DeleteAction implements Action {

    /**
     * 文件上传
     */
    @Resource
    private FileUploadTemplate fileUploadTemplate;

    public ActionResult doAction(Param param) {
        ActionResult actionResult = new ActionResult();
        FormResult formResult = new FormResult();
        List<Validate> vs = param.getValidates();
        Map<String, List<Validate>> map = new HashMap<String, List<Validate>>();
        String[] ids = param.getId().split(",");
        DB.startTx(() -> {
            for (String id : ids) {
                Object object = DB.get(param.getClazz(), id);
                List<Validate> validates = DB.deleteByDetailed(param.getClazz(), id, vs.toArray(new Validate[vs.size()]));
                if (validates != null) {
                    BeanMap beanMap = BeanMap.create(object);
                    for (Validate validate : vs) {
                        String key = StringUtil.getFmtStr(validate.getError());
                        if (key != null) {
                            Object val = beanMap.get(key);
                            validate.setError(validate.getError().replace(key, val + "").replace("{", "【").replace("}", "】"));
                        }
                    }
                    map.put("validates", validates);
                    return false;
                } else {
                    fileUploadTemplate.delete(object, param);
                }
            }
            return true;
        });
        List<Validate> validates = map.get("validates");
        formResult.setSuccess(true);
        if (validates != null) {
            validates.forEach(validate -> {
                formResult.putError(validate.getField(), validate.getError());
            });
            formResult.setSuccess(false);
        }
        actionResult.setFormResult(formResult);
        return actionResult;
    }
}
